import * as mars3d from 'mars3d'
import { initMap } from '@/components/utils/initMap'
// import map from 'core-js/fn/array/map'
import editorware from '../../utils/editorMiddleware'
import request from '../../../../utils/request'
// import store from '@/store'
// import cMenu from '../../contextMenu/utils/contextMenu'
// import { map } from 'core-js/core/array'
// import * as turf from '@turf/turf'
export default function render(data, flyTo) {
    let layer = undefined
    // if (data.type == 'billboard') {
    //     console.log(data, data.id)
    // }
    setTimeout(() => {
        switch (data.type) {
            case 'kml':
                // kml文件
                // layer = new mars3d.layer.Kml2JsonLayer(combinationPosition(data))
                // addLayerInMap(data, layer)
                break
            case 'billboard':
                // 图标点
                layer = new mars3d.graphic.BillboardEntity(combinationPosition(data))
                // console.log(combinationPosition(data))
                addLayerInMap(data, layer)
                break
            case 'box':
                // 盒子
                layer = new mars3d.graphic.BoxEntity(combinationPosition(data))
                addLayerInMap(data, layer)
                break
            case 'circle':
                // 圆
                layer = new mars3d.graphic.CircleEntity(combinationPosition(data))
                addLayerInMap(data, layer)
                break
            case 'ellipse':
                // 椭圆柱
                layer = new mars3d.graphic.EllipseEntity(combinationPosition(data))
                addLayerInMap(data, layer)
                break
            case 'polyline':
                // 线
                layer = new mars3d.graphic.PolylineEntity(combinationPosition(data))
                addLayerInMap(data, layer)
                break
            case 'curve':
                // 曲线
                layer = new mars3d.graphic.CurveEntity(combinationPosition(data))
                addLayerInMap(data, layer)
                break
            case 'rectangle':
                // 矩形
                layer = new mars3d.graphic.RectangleEntity(combinationPosition(data))
                addLayerInMap(data, layer)
                break
            case 'polygon':
                // 面
                // turf简化面坐标
                // let geo = JSON.parse(data.positions)
                // if (geo.length > 100) {
                //     geo.push(geo[0])
                //     let geojson = turf.polygon([geo])
                //     let options = { tolerance: 0.001, highQuality: true, mutate: true }
                //     let simplified = turf.simplify(geojson, options)
                //     // console.log(simplified.geometry.coordinates[0])
                //     data.positions = simplified.geometry.coordinates[0]
                // }

                // console.log(data.positions)
                layer = new mars3d.graphic.PolygonEntity(combinationPosition(data))
                addLayerInMap(data, layer)
                break
            case 'tif':
                // tif
                let tifData = JSON.parse(data.tifDataSet)
                // console.log(tifData)
                if (tifData && tifData.length > 0) {
                    renderTif(0, tifData, tifData.length - 1, data, flyTo)
                    // return
                    // tifData.forEach(v => {
                    //     layer = new mars3d.layer.ImageLayer({
                    //         url: v.url,
                    //         rectangle: {
                    //             xmin: v.minLongitude,
                    //             xmax: v.maxLongitude,
                    //             ymin: v.minLatitude,
                    //             ymax: v.maxLatitude
                    //         },
                    //         alpha: 1
                    //     })
                    //     layer.pid = data.id
                    //     // console.log(layer)
                    //     map.addLayer(layer)
                    //     if (data.isShow == '0') {
                    //         layer.show = false
                    //     }
                    //     editorware.coverageMap.set(layer.id, layer)
                    // })
                    // if (flyTo) {
                    //     map.flyToExtent({
                    //         xmin: data.xmin,
                    //         xmax: data.xmax,
                    //         ymin: data.ymin,
                    //         ymax: data.ymax,
                    //         height: 2100
                    //     })
                    // }
                }
                editorware.coverageMap.set(data.id, data)
                // layer = new mars3d.layer.ImageLayer(combinationPosition(data, flyTo))
                // addLayerInMap(data, layer)
                break
            case 'tile':
                // 金字塔瓦片
                // layer = new mars3d.graphic.RectangleEntity(combinationPosition(data))
                xyzLayers(data)
                break
            default:
                console.log('render switch default console:  ' + data.type)
        }
    }, 3000)
}
// tif渲染
function renderTif(index, array, total, data, flyTo) {
    // if (!editorware.coverageMap.get(data.id)) {

    // }
    let layer = new mars3d.layer.ImageLayer({
        // url: array[index].url,
        url: array[index].url,
        rectangle: {
            xmin: array[index].minLongitude,
            xmax: array[index].maxLongitude,
            ymin: array[index].minLatitude,
            ymax: array[index].maxLatitude
        },
        alpha: 1,
        pid: data.id,
        id: array[index].url
    })
    layer.pid = data.id
    if (data.isShow == '1') {
        map.addLayer(layer)
    }
    editorware.coverageMap.set(layer.id, layer)
    if (index < total) {
        renderTif(index + 1, array, total, data, flyTo)
    }

    return
    const xhr = new XMLHttpRequest()
    xhr.responseType = 'blob'
    xhr.onload = function() {
        let blobUrl = ''
        blobUrl = URL.createObjectURL(xhr.response)
        if (blobUrl) {
            // array[index].url = blobUrl
            let layer = new mars3d.layer.ImageLayer({
                // url: array[index].url,
                url: blobUrl,
                rectangle: {
                    xmin: array[index].minLongitude,
                    xmax: array[index].maxLongitude,
                    ymin: array[index].minLatitude,
                    ymax: array[index].maxLatitude
                },
                alpha: 1,
                pid: data.id,
                id: array[index].url
            })
            layer.pid = data.id

            if (data.isShow == '1') {
                map.addLayer(layer)
            }
            // if (data.isShow == '0') {
            //     layer.show = false
            // }
            editorware.coverageMap.set(layer.id, layer)
            if (index < total) {
                renderTif(index + 1, array, total, data, flyTo)
            }
            // if (flyTo) {
            //     map.flyToExtent({
            //         xmin: data.xmin,
            //         xmax: data.xmax,
            //         ymin: data.ymin,
            //         ymax: data.ymax,
            //         height: 2100
            //     })
            // }
        } else {
            throw new Error(`tif 图像渲染失败，${data.name}第${index + 1}张`)
        }
    }
    xhr.open('GET', array[index].url)
    xhr.send()
}
function combinationPosition(data, flyTo) {
    // new mars3d.graphic.PolygonEntity({
    //     name: 'd11',
    //     position: [106.389166, 29.514472, 394.1]
    // })
    // return
    if (data.type == 'billboard' || data.type == 'circle') {
        if (data.position) {
            let position = ''
            if (typeof data.position == 'string') {
                position = JSON.parse(data.position)
            } else {
                position = data.position
            }
            return {
                name: data.name,
                position: position,
                style: data.style
            }
        } else {
            let position = ''
            if (typeof data.positions == 'string') {
                position = JSON.parse(data.positions)
            } else {
                position = data.positions
            }
            if (data.type == 'billboard') {
                // console.log({
                //     name: data.name,
                //     position: position,
                //     style: data.style
                // })
            }
            return {
                name: data.name,
                position: position,
                style: data.style
            }
        }
    } else if (data.type == 'kml') {
    } else if (data.type == 'tif') {
        return {
            url: data.accessPath ? data.accessPath : data.layerUrl,
            rectangle: {
                xmin: data.minLongitude ? data.minLongitude : data.xmin,
                xmax: data.maxLongitude ? data.maxLongitude : data.xmax,
                ymin: data.minLatitude ? data.minLatitude : data.ymin,
                ymax: data.maxLatitude ? data.maxLatitude : data.ymax
            },
            alpha: 1,
            flyTo: flyTo
        }
    } else {
        return {
            name: data.name,
            positions: typeof data.positions == 'string' ? JSON.parse(data.positions) : data.positions,
            style: data.style
        }
    }
}
function addLayerInMap(data, layer) {
    if (!editorware.coverageMap.get(data.id)) {
        layer.id = data.id
        // layer.serveId = data.id
        // if (data.type == 'kml') {
        //     layer.options.type = data.type
        //     map.addLayer(layer)

        //     // bindClickAndRightClick(layer)
        // } else if (data.type == 'tif') {
        //     map.addLayer(layer)
        // } else {
        layer.options.type = data.type
        // layer.options.style.height = layer.options.style.zIndex * 10
        setTimeout(() => {
            // console.log(initMap, 1212)
            if (data.isShow == '1') {
                initMap.graphicLayer.addGraphic(layer)
            }
            if (layer.options.style.zIndex) {
                layer.options.style.height = layer.options.style.zIndex * 10
            }
        }, 1000)

        // if (data.isShow == '0') {
        //     layer.show = false
        // }
        // }
        if (data.type == 'polyline' && data.style.label.text == '0') {
            layer.setStyle({ label: { text: `${Math.ceil(Number(layer.distance))} m` } })
            request.postForm('/api/map/draw/modifyPlotDataById', { drawQueryString: JSON.stringify(layer) }).then(res => {
                if (res.code == 200) {
                    console.log('向后台提交最新数据成功')
                }
            })
        }
        if (data.type == 'polygon' && data.style.label.text == '0') {
            layer.setStyle({ label: { text: `${Math.ceil(Number(layer.area))} ㎡` } })
            request.postForm('/api/map/draw/modifyPlotDataById', { drawQueryString: JSON.stringify(layer) }).then(res => {
                if (res.code == 200) {
                    console.log('向后台提交最新数据成功')
                }
            })
        }
        editorware.coverageMap.set(data.id, layer)
        // 向后台提交最新数据
    }
}
// 金字塔瓦片渲染
function xyzLayers(data) {
    if (!editorware.coverageMap.get(data.id)) {
        let tileLayer = new mars3d.layer.XyzLayer({
            url: `${data.layerUrl}/{z}/{x}/{y}.png`,
            minimumLevel: 14,
            maximumLevel: 20,
            rectangle: { xmin: Number(data.xmin), xmax: Number(data.xmax), ymin: Number(data.ymin), ymax: Number(data.ymax) },
            pid: data.pid,
            id: data.id
        })
        if (data.isShow == '1') {
            map.addLayer(tileLayer)
        }
        editorware.coverageMap.set(data.id, tileLayer)
    }
}
// function propertys(params) {
//     // delete params.area
//     // delete params.area1
//     // delete params.distance
//     delete params.materialType
//     // delete params.zIndex
//     // delete params.tiltAreaUnit
//     // delete params.areaUnit
//     // delete params.tilt
//     // delete params.name
// }
// function bindClickAndRightClick(layer) {
//     layer
//         .on(mars3d.EventType.rightClick, function(a) {
//             let graphic = editorware.rightClickData
//             if (graphic) {
//                 graphic.stopEditing()
//             }
//             const commitData = {
//                 isShow: true,
//                 X: a.position.x,
//                 Y: a.position.y,
//                 type1: 'layerMenu',
//                 type2: 'layer',
//                 time: new Date().getTime()
//             }
//             store.commit('setContextMenu', commitData)
//             editorware.rightClickData = a.graphic
//         })
//         .on(mars3d.EventType.click, function(a) {
//             let graphic = editorware.rightClickData
//             if (graphic) {
//                 graphic.stopEditing()
//             }
//             // editorware.isFlyTo = true
//             editorware.rightClickData = a.graphic
//             store.commit('setContextMenu', { show: false })
//             cMenu.property()
//         })
// }
